package archer.framework.client.config;

import archer.framework.client.ArcherClientModule;
import archer.framework.client.exception.RemoteInvokeException;
import archer.framework.utils.ProfileUtils;
import archer.framework.utils.PropertiesUtils;
import archer.framework.utils.ValidateUtils;

import java.util.*;

/**
 * @author christ
 * @date 2016/5/16
 */
public class RemoteInvokeConfigFactory {

    private static Map<String, RemoteInvokeConfig> configs = null;

    private static Object lock = new Object();

    public static RemoteInvokeConfig getConfig(String mask) {

        if (ValidateUtils.isEmpty(mask)) {
            throw new RemoteInvokeException("不支持的远程服务");
        }

        synchronized (lock) {

            if (configs == null) {

                configs = new HashMap<String, RemoteInvokeConfig>();

                // 根据不同的模式选用不同的配置文件
                String configFile = ProfileUtils.getPropertiesFileName(ArcherClientModule.remoteInvokeConfigPath);

                Properties properties = new Properties();

                PropertiesUtils.loadFromClasspath(properties, configFile);

                String masks = PropertiesUtils.getString(properties, "remote.invoke.masks");

                if (ValidateUtils.isEmpty(masks)) {
                    throw new RemoteInvokeException("远程服务配置有误，请检查");
                }

                String[] maskList = masks.split(",");
                for (String each : maskList) {
                    RemoteInvokeConfig config = new RemoteInvokeConfig();

                    String hosts = PropertiesUtils.getString(properties, "remote.invoke.hosts." + each);

                    List<String> hostList = Arrays.asList(hosts.split(";"));
                    config.setHosts(hostList);
                    // use first host as default
                    config.setHost(hostList.get(0));

                    config.setApikey(PropertiesUtils.getString(properties, "remote.invoke.apikey." + each));
                    config.setApisecret(PropertiesUtils.getString(properties, "remote.invoke.apisecret." + each));
                    config.setLoginUrl(PropertiesUtils.getString(properties, "remote.invoke.login.urls." + each));
                    config.setVersion(PropertiesUtils.getString(properties, "remote.invoke.version." + each));
                    config.setTimeout(PropertiesUtils.getInt(properties, "remote.invoke.timeout." + each, 20000));
                    config.setMask(each);
                    configs.put(each, config);
                }
            }

        }

        return configs.get(mask);
    }
}
